package com.cxb.demotest.mq.rocketmq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 集群消费
 *      一般的消息消费模式，一个消息只被消费一次
 * 广播消费
 *      会重复消费消息
 *      不支持顺序消息
 *      客户端停机期间有消息，重启后会跳过处理
 * @author Xb
 */
public class BalanceConsumer {
    public static void main(String[] args) throws MQClientException {
        // 实例化消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group_consumer");

        // 指定namesrv
        consumer.setNamesrvAddr("127.0.0.1:9876");

        // 订阅topic
        consumer.subscribe("singleton_topic_1", "*");

        // 集群模式消费
        consumer.setMessageModel(MessageModel.CLUSTERING);
        // 广播模式消费
//        consumer.setMessageModel(MessageModel.BROADCASTING);

        // 注册回调函数、处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                try {
                    for (MessageExt msg : msgs) {
                        String topic = msg.getTopic();
                        String messageBody = new String(msg.getBody(), StandardCharsets.UTF_8);
                        String tags = msg.getTags();
                        System.out.println("收到消息：" + "topic:" + topic + ",tags:" + tags + ",messageBody:" + messageBody);
                    }
                } catch (Exception e){
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 启动消费者
        consumer.start();

        // 注销消费者
        System.out.println("Consume completed.");


    }
}
